<?php

namespace app\admin\controller;
class Download extends base
{

    //前置方法
    protected $beforeActionList = [
        'map' => ['only' => 'index'],
        'delfile' => ['only' => 'del'],
    ];


    /**
     * 删除文件
     */
    protected function delfile()
    {
        $file = $this->model->where('id',$this->request->param('id'))->value('file');
        if (!empty($file) && file_exists('./uploads/file/' . $file)) {
            @unlink('./uploads/file/' . $file);
        }
    }

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();
            if (!empty($data['start_time']) && !empty($data['end_time']) && (strtotime($data['start_time']) < strtotime($data['end_time']))) {
                $this->datas ['create_time'] = [
                    ['>', strtotime($data['start_time'])],
                    ['<', strtotime($data['end_time'])]
                ];
            }

            if (!empty($data['title'])) {
                $this->datas ['title'] = ['like', '%' . $data['title'] . '%'];
            }
        }
    }

    /**
     * 保存
     */
    public function save()
    {
        if (!$this->request->isPost()) {
            return ajax_info('请求失败');
        }
        $data = $this->request->post();

        $result = $this->validate($data, 'download');
        if (true !== $result) {
            return ajax_info($result);
        }

        if (!empty($data['id'])) {
            if ($data['file'] != $data['old_file']) {
                @unlink('./uploads/file/' . $data['old_file']);
            }
            return $this->update($data);
        }

        $res = $this->model->allowField(true)->save($data);
        if ($res) {
            return ajax_info('保存成功','y');
        } else {
            return ajax_info('添加失败');
        }
    }
}
